//
//  BPAppearView.swift
//  BPWeiBo
//
//  Created by 扒皮大叔 on 16/4/14.
//  Copyright © 2016年 apple. All rights reserved.

import UIKit
import SnapKit
class BPAppearView: UIView {
    
    var target: UIViewController = UIViewController()
    var appearBtn:[BPAppearBtn] = [BPAppearBtn]()
    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect)
        setUpUI()
        creatBtn()
    }
    
    //MARK:提供一个类方法共外界调用
    func show(target: UIViewController) {
        self.target = target
        target.view.addSubview(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:懒加载控件
    private func setUpUI() {
        //添加控件
        addSubview(maoBoLiImg)
        addSubview(logo)
        
        
        //设置约束
        self.maoBoLiImg.snp_makeConstraints { (make) in
            make.edges.equalTo(self.snp_edges)
        }
        self.logo.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY).offset(-280)
        }
    }
    
    //懒加载控件
    //毛玻璃效果的背景图片
    private lazy var maoBoLiImg:UIImageView = UIImageView(image: UIImage.snapshotScreen().applyLightEffect())
    //顶上的logo
    private lazy var logo:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))

    //懒加载模型数组
    private lazy var btnArr:[BPCompare] = {
        var arr = [BPCompare]()
        
        //获取路径
        let path = NSBundle.mainBundle().pathForResource("Compose", ofType: ".plist")
        //通过路径获取数组
        let arr1 = NSArray(contentsOfFile: path!) as! [[String : String]]
        //遍历数组,经数组里面的对象转换成对象
        for dic in arr1 {
            
            let appearModel = BPCompare.init(dict: dic)
            
            arr.append(appearModel)
            
        }
        return arr
    }()
    

    //MARK:创建按钮的数组
    let btnW:CGFloat = 80
    let btnH:CGFloat = 110

    private func creatBtn() {

        //设置每行按钮的个数
        let count2:Int = 3
        //设置他们之间的间距
        let margin:CGFloat = 20
        //设置在self中的x,y值
        let viewX:CGFloat = (ScreenWidth - (CGFloat(count2 - 1)*margin + CGFloat(count2)*btnW)) / 2 - margin
        for i in 0..<6 {
            let btn = BPAppearBtn()
            btn.composeItem = btnArr[i]
            btn.setTitle(btn.composeItem?.title, forState: .Normal)
            //设置文字居中
            btn.titleLabel?.textAlignment = .Center
            btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
            //let imgName = btnArr[i].icon
            let imgName = btn.composeItem?.icon
            btn.setImage(UIImage(named: imgName!), forState: .Normal)
            //获取按钮的x,y
            let btnX = margin + CGFloat(i % count2)*(margin + btnW)
            let btnY = margin + CGFloat(i / count2)*(margin + btnH)
            btn.frame = CGRect(x: btnX + viewX, y: btnY + ScreenHeight, width: btnW, height: btnH)
            
            //给按钮设置点击的方法
            btn.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)
            appearBtn.append(btn)

            addSubview(btn)
            
        }
    }
    //MARK:实现按钮的点击方法
    @objc private func btnDidClick(btn: BPAppearBtn) {

        for button in appearBtn {
            var scale:CGFloat  = 0
            if button == btn {
            scale = 3.0
            }else {
            scale = 0.1
            }
            //当点击这个按钮的时候跳转到编辑界面的控制器,并且让按钮虚化
            UIView.animateWithDuration(0.25, animations: { 
                button.transform = CGAffineTransformMakeScale(scale, scale)
                button.alpha = 0
                }, completion: { (_) in
                    //print("ok")
                    
            })

        }
        
        //执行完动画就去执行界面的 跳转
        guard let targetName = btn.composeItem?.target else {
            print("没有值")
           return
        }
        
        //根据字符串获取对应的控制器类型l
        let classType = NSClassFromString(targetName) as! UIViewController.Type
        //初始化后就可以得到我们的这个控制器
        let vc = classType.init()
        //加到nav上面
        let nav = UINavigationController(rootViewController: vc)
        
        //跳转控制器
        target.presentViewController(nav, animated: true, completion: {
            self.removeFromSuperview()
        })  

    }
    
    //MARK:在视图将要加载到父控制器的时候,执行动画方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        for (index,btn) in appearBtn.enumerate() {
        self.animated(btn, index: index, isUp: true)
        }
    }
    //MARK:在视图移除的时候调用
    //MARK:点击视图,移除view
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (index,btn) in appearBtn.reverse().enumerate() {
            self.animated(btn, index: index, isUp: false)
        }
    }
    
    //MARK:封装一个方法,将我们的对应的按钮的中心点y值进行改变,从而达到动画的效果
    private func animated(btn: BPAppearBtn,index:Int,isUp:Bool = false) {
        UIView.animateWithDuration(0.8, delay: Double(index) * 0.03, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: {
            //更改它的中心点
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + (isUp ? -350 : 350))
        }) { (_) in
            if !isUp {
            self.removeFromSuperview()
            }
        }
        
    }
}
